package cn.afactory.tygz.ui.sns;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.BaseImgView;
import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.model.PicsItem;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.utils.ImageLoaderUtil;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.ImageUploadType;
import cn.afactory.tygz.model.NearByUserInfo;
import cn.afactory.tygz.model.UploadFileInfo;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.adapter.UserProfileImgGridAdapter;
import cn.afactory.tygz.ui.base.utils.DateUtil;
import cn.afactory.tygz.ui.base.utils.ImageUtils;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.fragments.ProfileUserInfoFragment;
import cn.afactory.tygz.ui.fragments.ProfileUserSubjectFragment;
import cn.afactory.tygz.ui.fragments.ProfileUserTopicFragment;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * Created by Kenneth on 15/9/16.
 */
@ContentView(R.layout.ac_user_profile)
public class UserProfileActivity extends BaseActivity implements View.OnClickListener{

    public final static String USER_INFO_TAG = "UserInfo";

    private SnsControler mController;
    private UserInfo userProfileInfo;
    private UserProfileImgGridAdapter mAdapter;
    private List<UploadFileInfo> photoListData = new ArrayList<UploadFileInfo>();

    //info
    @ViewInject(R.id.user_profile_icon)
    private ImageView userProfileIcon;
    @ViewInject(R.id.user_profile_age)
    private TextView userProfileAge;
    @ViewInject(R.id.user_profile_city)
    private TextView userProfileCity;
    @ViewInject(R.id.user_profile_company)
    private TextView userProfileCompany;
    @ViewInject(R.id.user_profile_gender)
    private ImageView userProfileGender;
    @ViewInject(R.id.user_profile_class)
    private TextView userProfileClass;
    @ViewInject(R.id.user_profile_signature)
    private TextView userProfileSignature;

    //action
    @ViewInject(R.id.tv_add_follow_to)
    private TextView tv_add_follow_to;
    @ViewInject(R.id.tv_send_private_msg)
    private TextView tv_send_private_msg;
    @ViewInject(R.id.tv_add_black_list)
    private TextView tv_add_black_list;

    //photo
    @ViewInject(R.id.user_profile_grid_ll)
    private LinearLayout userPhotoLinearLayout;
    @ViewInject(R.id.user_profile_grid_rv)
    private RecyclerView userPhotoRecyclerView;
    @ViewInject(R.id.photo_album_add)
    private TextView userPhotoAlbumAdd;

    //fragment
    @ViewInject(R.id.user_profile_info_ll)
    private LinearLayout userProfileInfoll;
    @ViewInject(R.id.user_profile_info_title)
    private TextView userProfileInfoTitle;
    @ViewInject(R.id.user_profile_info_line)
    private View userProfileInfoLine;
    @ViewInject(R.id.user_profile_suject_ll)
    private LinearLayout userProfileSubjectll;
    @ViewInject(R.id.user_profile_suject_title)
    private TextView userProfileSubjectTitle;
    @ViewInject(R.id.user_profile_suject_line)
    private View userProfileSubjectLine;
    @ViewInject(R.id.user_profile_topic_ll)
    private LinearLayout userProfileTopicll;
    @ViewInject(R.id.user_profile_topic_title)
    private TextView userProfileTopicTitle;
    @ViewInject(R.id.user_profile_topic_line)
    private View userProfileTopicLine;
    @ViewInject(R.id.user_profile_fragment)
    private ViewPager userProfileFragment;


    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_USER_INFO_OK:
                if (msg.obj instanceof UserInfo) {
                    hideErrorPage(-1);
                    UserInfo userInfo = (UserInfo)msg.obj;
                    if (null != userInfo) {
                        userProfileInfo = userInfo;
                        applyDataToView(userInfo);
                    }
                }
                break;
            case SnsControler.MSG_GET_USER_INFO_KO:
                hideErrorPage(-1);
                showErrorPage(msg.arg1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startLoadDatas();
                    }
                });
                break;
            case SnsControler.MSG_GET_USER_ALBUMS_OK:
                if (msg.obj instanceof UploadFileInfoList) {
                    UploadFileInfoList uploadFileInfo = (UploadFileInfoList)msg.obj;
                    if (null != uploadFileInfo && null != uploadFileInfo.data && uploadFileInfo.data.size() > 0 ) {
                        userPhotoLinearLayout.setVisibility(View.VISIBLE);
                        photoListData.clear();
                        photoListData.addAll(uploadFileInfo.data);
                        mAdapter.setListData(photoListData);
                        if (SPUtils.isSelf(mContext, mUserId)) {
                            userPhotoAlbumAdd.setVisibility(View.VISIBLE);
                            userPhotoAlbumAdd.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    doAddNewImage();
                                }
                            });
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_USER_ALBUMS_KO:
                userPhotoLinearLayout.setVisibility(View.VISIBLE);
                break;

            case SnsControler.MSG_FOLLOWED_USER_OK:
                tv_add_follow_to.setText(getString(R.string.label_btn_cancel_attention));
                break;
            case SnsControler.MSG_FOLLOWED_USER_KO:
                LocalUtils.showToast(UserProfileActivity.this,(String)msg.obj);
                break;
            case SnsControler.MSG_UNFOLLOWED_USER_OK:
                tv_add_follow_to.setText(getString(R.string.label_btn_attention));
                break;
            case SnsControler.MSG_UNFOLLOWED_USER_KO:
                LocalUtils.showToast(UserProfileActivity.this,(String)msg.obj);
                break;

            case SnsControler.MSG_BLACK_USER_OK:
                tv_add_black_list.setText(getString(R.string.label_btn_cancel_black));
                break;
            case SnsControler.MSG_BLACK_USER_KO:
                LocalUtils.showToast(UserProfileActivity.this,(String)msg.obj);
                break;
            case SnsControler.MSG_UNBLACK_USER_OK:
                tv_add_black_list.setText(getString(R.string.label_btn_black));
                break;
            case SnsControler.MSG_UNBLACK_USER_KO:
                LocalUtils.showToast(UserProfileActivity.this,(String)msg.obj);
                break;
            default:
                break;
        }
    }

    /**
     * 跳转到个人主页
     * @param context
     * @param userId
     */
    public static void gotoUserProfile(Context context,long userId,String nickName){
        Intent intent = new Intent(context,UserProfileActivity.class);
        intent.putExtra(SPUtils.EXTRA_USER_ID, userId);
        intent.putExtra(SPUtils.EXTRA_NICK_NAME, nickName);
        context.startActivity(intent);
    }

    private long mUserId;
    private String mUserName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        Intent intent = getIntent();
        mUserId = intent.getLongExtra(SPUtils.EXTRA_USER_ID, 0);
        mUserName = intent.getStringExtra(SPUtils.EXTRA_NICK_NAME);

        mController = new SnsControler(mContext,mUIHandler,"userInfo");
        initView();
        initData();
    }

    private void initView() {
        initTitleBar();
        initCameraPop();
        initActionView();
        initUserProfilePhotoGrid();
    }

    private void initActionView() {
        if (mUserId == SPUtils.getUid(this)) {
            tv_add_follow_to.setTextColor(getResources().getColor(R.color.translucent_50_dark));
            tv_add_follow_to.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_rect_gray_empty));
            tv_send_private_msg.setTextColor(getResources().getColor(R.color.translucent_50_dark));
            tv_send_private_msg.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_rect_gray_empty));
            tv_add_black_list.setTextColor(getResources().getColor(R.color.translucent_50_dark));
            tv_add_black_list.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_rect_gray_empty));
            return;
        }

        tv_add_follow_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关注
                if (userProfileInfo.isFocus) {
                    mController.doUnFollowUser(userProfileInfo.id);
                } else {
                    mController.doFollowUser(userProfileInfo.id);
                }
            }
        });

        tv_send_private_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送私信
                if(userProfileInfo == null){
                    return ;
                }
                NaviUtils.gotoMessageDetail(UserProfileActivity.this,
                        userProfileInfo.id,
                        userProfileInfo.nickName,
                        userProfileInfo.userIcon);
            }
        });

        tv_add_black_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加黑名单
                if (userProfileInfo.isBlack) {
                    mController.doUnBlackUser(userProfileInfo.id);
                } else {
                    mController.doBlackUser(userProfileInfo.id);
                }
            }
        });
    }

    private void initUserProfilePhotoGrid() {
        mAdapter = new UserProfileImgGridAdapter(photoListData);
        userPhotoRecyclerView.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new UserProfileImgGridAdapter.MyItemClickListener() {
            @Override
            public void OnItemClickListener(View v, int position) {
                //添加图片点击相应
                if (TimeUtil.isFastDoubleClick()) {
                    return;
                }
                List<UploadFileInfo> listData = mAdapter.getListData();
                if (listData != null) {
                    ArrayList<PicsItem> list = new ArrayList<>();
                    for (UploadFileInfo uploadFileInfo : listData) {
                        PicsItem picsItem = new PicsItem();
                        picsItem.image = uploadFileInfo.url;
                        list.add(picsItem);
                    }
                    mContext.startActivity(PageBigImageActivity.getIntent(mContext, list, position, false, false));
                }
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        userPhotoRecyclerView.setLayoutManager(layoutManager);
        userPhotoRecyclerView.addItemDecoration(new BaseItemDecoration());
    }

    private void initUserProfileInfoFragment() {
        userProfileInfoll.setOnClickListener(this);
        userProfileSubjectll.setOnClickListener(this);
        userProfileTopicll.setOnClickListener(this);

        UserProfileViewPagerAdapter userProfileViewPagerAdapter = new UserProfileViewPagerAdapter(getSupportFragmentManager());
        userProfileFragment.setAdapter(userProfileViewPagerAdapter);
        userProfileFragment.setOffscreenPageLimit(3);
        userProfileFragment.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int idx) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        switchTab(R.id.user_profile_info_ll);
    }

    private void initTitleBar(){
        setTitleText(mUserName);
    }

    private void initData(){
        startLoadDatas();
    }

    private void startLoadDatas() {
        if(mUserId >= 0){
            mController.doGetUserInfo(mUserId);
            mController.doGetUserAlbums(mUserId);
        }
    }

    private void applyDataToView(UserInfo userInfo) {
        setTitleText(null == userInfo.nickName ? "个人主页" : userInfo.nickName);

        String imageUrl = userInfo.userIcon;
        if (!TextUtils.isEmpty(imageUrl)) {
            userProfileIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
            int nwidth = 60;
            BaseImgView.loadimg(userProfileIcon, ImageUtils.getThumbnailFullPath(imageUrl,
                            nwidth + "x" +
                                    nwidth), R.drawable.ic_pic_loading_default_small,
                    R.drawable.ic_pic_loading_default_small, R.drawable.ic_pic_loading_default_small, ImageScaleType.EXACTLY,
                    nwidth,
                    nwidth, 20);
        } else {
            userProfileIcon.setImageResource(R.drawable.ic_pic_loading_default_small);
        }

        if (userInfo.birth > 0) {
            userProfileAge.setText(DateUtil.getAgeByNorth(userInfo.birth)+"岁");
        } else {
            userProfileAge.setText("岁");
        }

        if (null != userInfo.cityName && userInfo.cityName.trim().length()>0) {
            userProfileCity.setText(userInfo.cityName);
        } else {
            userProfileCity.setText("上海");
        }

        if (null != userInfo.company && userInfo.company.trim().length()>0){
            userProfileCompany.setText(userInfo.company);
        } else {
            userProfileCompany.setText("");
        }

        if (userInfo.sex == 0) {
            userProfileGender.setImageResource(R.drawable.tag_male);
        } else {
            userProfileGender.setImageResource(R.drawable.tag_female);
        }

        if (userInfo.level >= 0) {
            userProfileClass.setText(userInfo.level+"级");
        }

        if (null != userInfo.signature && userInfo.signature.trim().length()>0) {
            userProfileSignature.setText(userInfo.signature);
        } else {
            userProfileSignature.setText("");
        }

        if(userProfileInfo.isFocus){
            tv_add_follow_to.setText(getString(R.string.label_btn_cancel_attention));
        }else{
            tv_add_follow_to.setText(getString(R.string.label_btn_attention));
        }

        if(userProfileInfo.isBlack){
            tv_add_black_list.setText(getString(R.string.label_btn_cancel_black));
        }else{
            tv_add_black_list.setText(getString(R.string.label_btn_black));
        }

        initUserProfileInfoFragment();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_profile_info_ll:
                switchTab(R.id.user_profile_info_ll);
                break;
            case R.id.user_profile_topic_ll:
                switchTab(R.id.user_profile_topic_ll);
                break;
            case R.id.user_profile_suject_ll:
                switchTab(R.id.user_profile_suject_ll);
                break;
        }
    }

    //tab之间切换
    private void switchTab(int id) {
        clearTaskStatus();

        switch (id){
            case R.id.user_profile_info_ll:
                userProfileFragment.setCurrentItem(0, false);
                userProfileInfoTitle.setTextColor(getResources().getColor(R.color.btn_nearby_bg));
                userProfileInfoLine.setVisibility(View.VISIBLE);
                break;
            case R.id.user_profile_suject_ll:
                userProfileFragment.setCurrentItem(1, false);
                userProfileSubjectTitle.setTextColor(getResources().getColor(R.color.btn_nearby_bg));
                userProfileSubjectLine.setVisibility(View.VISIBLE);
                break;
            case R.id.user_profile_topic_ll:
                userProfileFragment.setCurrentItem(2, false);
                userProfileTopicTitle.setTextColor(getResources().getColor(R.color.btn_nearby_bg));
                userProfileTopicLine.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void clearTaskStatus(){
        userProfileInfoTitle.setTextColor(Color.parseColor("#535353"));
        userProfileInfoLine.setVisibility(View.GONE);

        userProfileTopicTitle.setTextColor(Color.parseColor("#535353"));
        userProfileTopicLine.setVisibility(View.GONE);

        userProfileSubjectTitle.setTextColor(Color.parseColor("#535353"));
        userProfileSubjectLine.setVisibility(View.GONE);
    }


    public class BaseItemDecoration extends RecyclerView.ItemDecoration {

        int offset = mContext.getResources().getDimensionPixelOffset(R.dimen.margin_5dp);
        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            // TODO Auto-generated method stub
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(offset, offset, offset, offset);
        }

    }

    class UserProfileViewPagerAdapter extends FragmentPagerAdapter {
        public UserProfileViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int idx) {
            Fragment fragment = null;
            switch (idx) {
                case 0:
                    fragment = new ProfileUserInfoFragment();
                    break;
                case 1:
                    fragment = new ProfileUserSubjectFragment();
                    break;
                case 2:
                    fragment = new ProfileUserTopicFragment();
                    break;
            }

            Bundle bundle = new Bundle();
            bundle.putSerializable(UserProfileActivity.USER_INFO_TAG, userProfileInfo);
            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    //添加新图片
    private void doAddNewImage(){
        if(mCameraPop != null) {
            mCameraPop.showMenu(userPhotoAlbumAdd);
        }
    }

    private CameraPop mCameraPop;
    private String mImagePath = null;
    private int mFileFiledId = -1;
    //初始化图片的菜单项
    private void initCameraPop(){
        mCameraPop = new CameraPop(this, new CameraPopListener() {
            @Override
            public void onCamreaClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_CAMERA);
                mCameraPop.process();
            }

            @Override
            public void onPickClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_GALLERY);
                mCameraPop.process();
            }

            @Override
            public void onDelClick() {

            }
        }, new CameraImageListener() {
            @Override
            public void onSelectedAsy(String imgPath) {
//                if(imgPath != null){
//                    mImagePath = imgPath;
//                    mDeleteView.setVisibility(View.VISIBLE);
//                    ImageLoaderUtil.loadLocalImage(mThumbImageView, imgPath);
//                }
            }
        });
    }

    /**
     * 上传图片
     */
    private void doUploadImage(){
        showLoadingView("");
        NetManager.getInstance(this).doUploadImage(mImagePath, ImageUploadType.FORUMS,
                new OnResponseListener<UploadFileInfoList>() {
                    @Override
                    public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if(isOK && result != null && result.data != null && result.data.size() > 0){
                            mFileFiledId = result.data.get(0).fileId;
                        }else{
                            LocalUtils.showToast(UserProfileActivity.this,"图片上传失败！");
                        }
                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(UserProfileActivity.this, errorMessage);
                    }

                });
    }
}
